package branch.feature.advertisement

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mynewsapp.databinding.ActivityMainLoginAdBinding
import com.google.firebase.auth.FirebaseAuth

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainLoginAdBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainLoginAdBinding.inflate(layoutInflater)

        setContentView(binding.root)

        binding.apply {
            register.setOnClickListener {
                var intent = Intent(this@LoginActivity, RegisterActivity::class.java)

                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

                startActivity(intent)
                finish()
            }

            loginButton.setOnClickListener {
                FirebaseAuth.getInstance().signInWithEmailAndPassword(
                    etLoginEmail.text.toString(),
                    etLoginPassword.text.toString()
                ).addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        val firebaseUser = task.result!!.user!!
                        Toast.makeText(
                            this@LoginActivity,
                            "登录成功", Toast.LENGTH_SHORT
                        ).show()


                        val intent = Intent(this@LoginActivity, MainActivity::class.java)
                        intent.flags =
                            Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

                        intent.putExtra("user_id", firebaseUser.uid)
                        intent.putExtra("user_email", firebaseUser.email)

                        startActivity(intent)

                        finish()
                    } else {
                        Toast.makeText(
                            this@LoginActivity,
                            task.exception!!.message.toString(),
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    }
                }
            }
        }
    }
}